package com.afd.ozblip.image;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.afd.ozblip.activity.R;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.TextView;

public class LoadImage {
	private ExecutorService executorService; // 固定五个线程来
	private ImageMemoryCache memoryCache;// 内存缓存
	private ImageFileCache fileCache;// 文件缓存
	private Map<String, ImageView> taskMap;// 存放任务
	private Context context;
	private TextView loadTv;
	private Resources res;

	public LoadImage(Context c) {
		executorService = Executors.newFixedThreadPool(10);
		memoryCache = new ImageMemoryCache();
		fileCache = new ImageFileCache();
		taskMap = new HashMap<String, ImageView>();
		context = c;
		res = c.getResources();
	}

	public void addTask(String url, ImageView img) {
		String joinURL = url;
		System.out.println(joinURL);
		Bitmap bitmap = memoryCache.getBitmapFromCache(joinURL);
		if (bitmap != null) {
			img.setImageBitmap(bitmap);
		} else {
			synchronized (taskMap) {
				taskMap.put(Integer.toString(img.hashCode()), img);
			}
			img.setTag(joinURL);
			doTask();
		}
	}

	public void addTask(String url, ImageView img, TextView loadTv) {
		this.loadTv = loadTv;
		String joinURL = url;
		System.out.println(joinURL);
		Bitmap bitmap = memoryCache.getBitmapFromCache(joinURL);
		if (bitmap != null) {
			img.setImageBitmap(bitmap);
		} else {
			synchronized (taskMap) {
				taskMap.put(Integer.toString(img.hashCode()), img);
			}
			img.setTag(joinURL);
			doTask();
		}
	}

	public void doTask() {
		synchronized (taskMap) {
			Collection<ImageView> con = taskMap.values();
			for (ImageView i : con) {
				if (i != null) {
					if (i.getTag() != null) {
						loadImage((String) i.getTag(), i);
					}
				}
			}
			taskMap.clear();
		}
	}

	private void loadImage(String url, ImageView img) {
		/*** 加入新的任务 ***/
		executorService.submit(new TaskWithResult(new TaskHandler(url, img),
				url));
	}

	/*** 获得一个图片,从三个地方获取,首先是内存缓存,然后是文件缓存,最后从网络获取 ***/
	private Bitmap getBitmap(String url) {
		// 从内存缓存中获取图片
		Bitmap result;
		result = memoryCache.getBitmapFromCache(url);
		if (result == null) {
			// 文件缓存中获取
			result = fileCache.getImage(url);
			if (result == null) {
				// 从网络获取
				result = ImageGetForHttp.downloadBitmap(url);
				if (result == null) {
					result = BitmapFactory.decodeResource(
							context.getResources(), R.drawable.default_pic);
				}
				memoryCache.addBitmapToCache(url, result);
				fileCache.saveBmpToSd(result, url);
			} else {
				// 添加到内存缓存
				memoryCache.addBitmapToCache(url, result);
			}
		}
		return result;
	}

	/**
	 * 回调接口
	 * 
	 * @author onerain
	 * 
	 */
	public interface ImageCallBack {
		public void imageLoad(ImageView imageView, Bitmap bitmap);
	}

	/*** 完成消息 ***/
	private class TaskHandler extends Handler {
		String url;
		ImageView img;

		public TaskHandler(String url, ImageView img) {
			this.url = url;
			this.img = img;
		}

		@Override
		public void handleMessage(Message msg) {
			/*** 查看imageview需要显示的图片是否被改变 ***/
			if (img.getTag().equals(url)) {
				if (msg.obj != null) {
					Bitmap bitmap = (Bitmap) msg.obj;
					img.setImageBitmap(bitmap);
					if (loadTv != null) {
						loadTv.setVisibility(8);
					}
				}
			}
		}
	}

	/*** 子线程任务 ***/
	private class TaskWithResult implements Callable<String> {
		private String url;
		private Handler handler;

		public TaskWithResult(Handler handler, String url) {
			this.url = url;
			this.handler = handler;
		}

		@Override
		public String call() throws Exception {
			Message msg = new Message();
			msg.obj = getBitmap(url);
			if (msg.obj != null) {
				handler.sendMessage(msg);
			}
			return url;
		}

	}
}